<template>
  <div class="form-container">
    <h2>{{ name }}</h2>
    <form @submit.prevent="handleSubmit">
      <div v-for="field in processedFields" :key="field.id" class="form-group">
        <label :for="`field-${field.id}`">{{ field.name }}</label>

        <!-- 文本输入框 -->
        <input v-if="field.type === 'input'" :id="`field-${field.id}`" type="text" v-model="field.answer"
          :required="field.isRequired" />

        <!-- 单选框 -->
        <div v-else-if="field.type === 'radio'" class="options">
          <label v-for="option in parseOptions(field.value)" :key="option">
            <input type="radio" :name="`field-${field.id}`" :value="option" v-model="field.answer"
              :required="field.isRequired" />
            {{ option }}
          </label>
        </div>

        <!-- 多选框（修复后的版本） -->
        <div v-else-if="field.type === 'checkbox'" class="options">
          <label v-for="option in parseOptions(field.value)" :key="option">
            <input type="checkbox" :value="option" :checked="field.answerList.includes(option)"
              @change="handleCheckboxChange(field, option, $event)" />
            {{ option }}
          </label>
        </div>

        <!-- 文件上传 -->
        <input v-else-if="field.type === 'file'" type="file" accept="image/*" @change="handleFileChange(field, $event)"
          :required="field.isRequired" />

        <!-- 默认 input -->
        <input v-else type="text" v-model="field.answer" :required="field.isRequired" />
      </div>

      <div class="submit-wrapper">
        <button type="submit" class="submit-btn" :disabled="isSubmitting">
          {{ isSubmitting ? '提交中...' : '提交' }}
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import { submitForm, uploadFile } from '@/api/cd/form'

export default {
  name: 'DynamicForm',
  props: {
    formFields: {
      type: Array,
      required: true,
      default: () => [],
      validator: (fields) => {
        return fields.every(f => f.id && f.name && f.type)
      }
    },
    name: {
      type: String,
      default: '问卷填写'
    },
    formId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isSubmitting: false
    }
  },
  computed: {
    processedFields() {
      return this.formFields.map(field => {
        // 确保每个字段都有独立的数据引用
        const baseField = { ...field }
        if (field.type === 'checkbox') {
          return {
            ...baseField,
            answerList: Array.isArray(field.answerList)
              ? [...field.answerList]
              : []
          }
        }
        return baseField
      })
    }
  },
  methods: {
    parseOptions(value) {
      if (!value || value === '0') return []
      return value.split(',')
    },

    handleFileChange(field, event) {
      const file = event.target.files[0];
      if (file && file.type.startsWith('image/')) {
        // 生成本地预览
        const reader = new FileReader();
        reader.onload = (e) => {
          field.previewUrl = e.target.result;
        };
        reader.readAsDataURL(file);

        // 上传文件并获取URL
        const formData = new FormData();
        formData.append('fileName', file);
        // axios.post('/api/upload/image', formData).then(response => {
        //   field.answer = response.data; // 假设返回的是文件的URL
        // }).catch(error => {
        //   console.error('文件上传失败:', error);
        //   event.target.value = null; // 清空选择
        // });
        uploadFile(formData).then(response => {
          // this.open = false;
          // this.options.img = process.env.VUE_APP_BASE_API + response.imgUrl;
          // store.commit('SET_AVATAR', this.options.img);
          // this.$modal.msgSuccess("修改成功");
          // this.visible = false;
          //console.log(response);
          field.answer = response.imgUrl;
        });
      } else {
        this.$message.error('请上传图片文件');
        event.target.value = null; // 清空选择
      }
    },

    handleCheckboxChange(field, option, event) {
      const isChecked = event.target.checked
      const newValue = isChecked
        ? [...field.answerList, option]
        : field.answerList.filter(item => item !== option)

      // 确保响应式更新
      this.$set(field, 'answerList', newValue)
    },

    async handleSubmit() {
      if (this.isSubmitting) return;
      this.isSubmitting = true;

      try {
        // 验证必填文件
        const missingFiles = this.processedFields.filter(
          field => field.type === 'file' && field.isRequired && !field.answer
        );
        if (missingFiles.length > 0) {
          this.$message.error('请上传所有必填文件');
          return;
        }

        // 构建提交数据（包含 name 字段）
        const formData = this.processedFields.map(field => {
          const baseData = {
            id: field.id,
            type: field.type,
            name: field.name // 新增 name 字段
          };
          if (field.type === 'checkbox') {
            return { ...baseData, value: field.answerList || [] };
          }
          return { ...baseData, value: field.answer || '' };
        });

        const response = await submitForm({
          formId: this.formId,
          data: JSON.stringify(formData)
        });

        if (response.code === 200) {
          this.$emit('submit-success', response);
        } else {
          this.$emit('submit-error', response);
        }
      } catch (error) {
        console.error('提交失败:', error);
        this.$emit('submit-error', error);
      } finally {
        this.isSubmitting = false;
      }
    }
  }
}
</script>

<style scoped>
.form-container {
  max-width: 700px;
  margin: 0 auto;
  background: #fff;
  padding: 24px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

h2 {
  text-align: center;
  margin-bottom: 24px;
  font-size: 24px;
  color: #333;
}

.form-group {
  margin-bottom: 28px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.form-group>label {
  display: block;
  font-weight: bold;
  margin-bottom: 8px;
  font-size: 15px;
  color: #2c3e50;
  border-left: 4px solid #007bff;
  padding-left: 10px;
}

input[type="text"],
input[type="file"] {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ccc;
  border-radius: 6px;
  font-size: 14px;
  box-sizing: border-box;
  transition: border-color 0.3s ease;
}

input[type="text"]:focus,
input[type="file"]:focus {
  border-color: #007bff;
  outline: none;
}

.options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 6px;
}

.options label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: normal;
  font-size: 14px;
  color: #333;
  border-left: none;
  padding-left: 0;
}

.submit-wrapper {
  text-align: center;
  margin-top: 10px;
}

.submit-btn {
  padding: 12px 24px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s ease;
  min-width: 200px;
}

.submit-btn:hover {
  background: #0056b3;
}

.submit-btn:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

@media (max-width: 600px) {
  .options {
    flex-direction: row;
    overflow-x: auto;
  }

  .options label {
    white-space: nowrap;
    min-width: max-content;
  }

  .form-group {
    margin-bottom: 20px;
    padding: 12px;
  }

  .form-group>label {
    font-size: 14px;
  }
}
</style>